package com.xuelang.pipeline.app.application.converter;

import com.xuelang.hiforce.base.utils.bean.SpringApplicationContextHolder;
import com.xuelang.jadp.client.sys.dto.UserInfoDTO;
import com.xuelang.pipeline.client.application.dto.ApplicationDTO;
import com.xuelang.pipeline.client.common.constant.Constant;
import com.xuelang.pipeline.domain.application.Application;
import com.xuelang.sys.app.sys.UserManagerService;
import org.apache.commons.lang3.StringUtils;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.factory.Mappers;

import java.util.Objects;

/**
 * 应用DTO与应用实体转换器
 *
 * @author xiwen.zxg
 * @since 2024/5/15
 */
@Mapper
public interface ApplicationDTOToApplicationConverter {
    ApplicationDTOToApplicationConverter INSTANCE = Mappers.getMapper(ApplicationDTOToApplicationConverter.class);

    /**
     * Application转化为ApplicationDTO
     * @param application
     * @return
     */
    ApplicationDTO applicationToApplicationDTO(Application application);

    /**
     * ApplicationDTO转化为Application
     * @param applicationDTO
     * @return
     */
    Application applicationDTOToApplication(ApplicationDTO applicationDTO);

    @AfterMapping
    default void afterMappingToDTO(Application source, @MappingTarget ApplicationDTO target) {
        if (source != null && StringUtils.isNotBlank(source.getCreatorId())) {
            UserManagerService userManagerService = SpringApplicationContextHolder.getSpringBean(UserManagerService.class);
            UserInfoDTO user = userManagerService.getUserById(source.getCreatorId());
            if (Objects.nonNull(user)) {
                target.setCreator(user.getRealName());
            }else{
                target.setCreator(Constant.UNKNOWN_USER);
            }
        }
    }
}
